Crate stderrlog

source ·
Expand description

A simple logger to provide semantics similar to what is expected of most UNIX utilities by logging to stderr and the higher the verbosity the higher the log level. It supports the ability to provide timestamps at different granularities. As well as colorizing the different log levels.

Simple Use Case

use log::*;

fn main() {
    stderrlog::new().module(module_path!()).init().unwrap();

    error!("some failure");

    // ...
}

StructOpt Example

use log::*;
use structopt::StructOpt;

/// A StructOpt example
#[derive(StructOpt, Debug)]
#[structopt()]
struct Opt {
    /// Silence all output
    #[structopt(short = "q", long = "quiet")]
    quiet: bool,
    /// Verbose mode (-v, -vv, -vvv, etc)
    #[structopt(short = "v", long = "verbose", parse(from_occurrences))]
    verbose: usize,
    /// Timestamp (sec, ms, ns, none)
    #[structopt(short = "t", long = "timestamp")]
    ts: Option<stderrlog::Timestamp>,
}

fn main() {
    let opt = Opt::from_args();

    stderrlog::new()
        .module(module_path!())
        .quiet(opt.quiet)
        .verbosity(opt.verbose)
        .timestamp(opt.ts.unwrap_or(stderrlog::Timestamp::Off))
        .init()
        .unwrap();
    trace!("trace message");
    debug!("debug message");
    info!("info message");
    warn!("warn message");
    error!("error message");
}

docopt Example

use log::*;
use docopt::Docopt;
use serde::Deserialize;

const USAGE: &'static str = "
Usage: program [-q] [-v...]
";

#[derive(Debug, Deserialize)]
struct Args {
    flag_q: bool,
    flag_v: usize,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.deserialize())
                            .unwrap_or_else(|e| e.exit());

    stderrlog::new()
            .module(module_path!())
            .quiet(args.flag_q)
            .timestamp(stderrlog::Timestamp::Second)
            .verbosity(args.flag_v)
            .init()
            .unwrap();
    trace!("trace message");
    debug!("debug message");
    info!("info message");
    warn!("warn message");
    error!("error message");

    // ...
}

clap Example

use clap::{Arg, App, crate_version};
use log::*;
use std::str::FromStr;

fn main() {
    let m = App::new("stderrlog example")
        .version(crate_version!())
        .arg(Arg::with_name("verbosity")
             .short('v')
             .takes_value(true)
             .multiple(true)
             .help("Increase message verbosity"))
        .arg(Arg::with_name("quiet")
             .short('q')
             .help("Silence all output"))
        .arg(Arg::with_name("timestamp")
             .short('t')
             .help("prepend log lines with a timestamp")
             .takes_value(true)
             .possible_values(&["none", "sec", "ms", "ns"]))
        .get_matches();

    let verbose = m.occurrences_of("verbosity") as usize;
    let quiet = m.is_present("quiet");
    let ts = m.value_of("timestamp").map(|v| {
        stderrlog::Timestamp::from_str(v).unwrap_or_else(|_| {
            clap::Error::raw(clap::ErrorKind::InvalidValue, "invalid value for 'timestamp'").exit()
        })
    }).unwrap_or(stderrlog::Timestamp::Off);

    stderrlog::new()
        .module(module_path!())
        .quiet(quiet)
        .verbosity(verbose)
        .timestamp(ts)
        .init()
        .unwrap();
    trace!("trace message");
    debug!("debug message");
    info!("info message");
    warn!("warn message");
    error!("error message");
}

log Compatibility

The 0.5.x versions of stderrlog aim to provide compatibility with applications using log >= 0.4.11.

Rust Compatibility

stderrlog is serious about backwards compat. stderrlog pins the minimum required version of Rust in the CI build. Bumping the minimum version of Rust is a minor breaking change and requires a minor version to be bumped.

The minimum supported Rust version for this release is 1.36.0.

Module Level Logging

stderrlog has the ability to limit the components which can log. Many crates use log but you may not want their output in your application. For example hyper makes heavy use of log but when your application receives -vvvvv to enable the trace!() messages you don’t want the output of hyper’s trace!() level.

To support this stderrlog includes a module() method allowing you to specify the modules that are allowed to log. The examples above use the module_path!() macro to enable logging only for the binary itself but none of its dependencies. To enable logging from extra crates just add another call to module() with the name of the crate. To enable logging for only a module within that crate specify crate::module to module(). crates and modules will be named the same way would would include them in source code with use (e.g. some-crate would be some_crate).

For a good example of how the module level logging works see the large-example crate under examples, you’ll want to run the following binaries to see all the examples:

  • cargo run --bin large-example --
  • cargo run --bin another --
  • cargo run --bin yet --

Features

stderrlog has the following default crate features, which can be disabled to reduce the number of dependencies:

  • timestamps: Provides support for log timestamp prefixes (uses the chrono crate).

Structs

Data specific to this logger

Enums

ColorChoice represents the color preferences of an end user.
State of the timestamping in the logger.

Functions

creates a new stderr logger